﻿using Bing.Maps;
using Windows.Devices.Geolocation;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace LocationTracking_WinRT_CS
{
    public sealed partial class MainPage : Page
    {
        Pushpin gpsPushpin;

        public MainPage()
        {
            this.InitializeComponent();

            //Create a pushpin for the GPS location and add it to the map
            gpsPushpin = new Pushpin()
            {
                Visibility = Windows.UI.Xaml.Visibility.Collapsed
            };

            MyMap.Children.Add(gpsPushpin);

            Geolocator geolocator = new Geolocator();
            geolocator.PositionChanged += geolocator_PositionChanged;
        }

        private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            // Need to get back onto UI thread before updating location information
            this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(
            () =>
            {
                //Get the current location
                Location location = new Location(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);

                //Update the position of the GPS pushpin
                MapLayer.SetPosition(gpsPushpin, location);

                //Make GPS pushpin visible
                gpsPushpin.Visibility = Windows.UI.Xaml.Visibility.Visible;

                //Update the map view to the current GPS location
                MyMap.SetView(location, 17);
            }));
        }

        private void Test_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {

        }
    }
}
